package com.testing.splogin.controller;
import com.testing.splogin.model.Result;
import com.testing.splogin.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.font.TrueTypeFont;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping(value = "/user",produces = "application/json")
public class UserController {
@Autowired
    UserService userService;

@PostMapping("/login")
    @ApiOperation("登录接口")
    public Result login(@ApiParam(value="用户名",allowEmptyValue = true, required = false) @RequestParam(required = false)
                        String username,
                        String password,
                        HttpServletRequest request,HttpServletResponse response){
    HttpSession session=request.getSession();
    String sessionId=session.getId();
    System.out.println("sessionid是"+sessionId);
    session.setMaxInactiveInterval(120);
    Cookie[] cookies=request.getCookies();
    if(cookies!=null){
        for(Cookie cookie:cookies){
            System.out.println(cookie.getName()+":"+cookie.getValue());
        }
    }
    Object loginName=session.getAttribute("loginName");
    if(loginName!=null){
        if(loginName.toString().equals(username)){
            return new Result(-100,"不能再次登录",
                    "您"+loginName+"已经登录过了");
        }else{
            return new Result(-101,"不能再次登录",
                    "已经有另一个用户"+loginName+"登录过了");
        }
    }
    Result login=userService.login(username,password);
    if(login.getCode()==200){
        session.setAttribute("loginName",username);
        Cookie jsessionCookie=new Cookie("JSESSIONID",sessionId);
        jsessionCookie.setMaxAge(120);
        jsessionCookie.setPath("/");
        response.addCookie(jsessionCookie);
    }
    return login;

@GetMapping("/logout")
    public Result logout(HttpServletRequest request){
    HttpSession session=request.getSession();
    String sessionId=session.getId();
        System.out.println("登出接口中的sessionId是"+sessionId);
        session.invalidate();
        return new Result(200,"登出成功","不管有没有用户，反正都帮你注销了");
}
}
}